package self.test.project.streamDemo;

import cn.hutool.core.collection.CollUtil;
import java.util.*;
import java.util.stream.Collectors;

public class StreamDealDemo {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("a", "a", "c", "c", "b", "d");
        Map<String,List<String>> map = new HashMap<>();
        map.put("a",Arrays.asList("a"));
        map.put("b",Arrays.asList("b"));
        map.put("c",Arrays.asList("c"));
        System.out.println(listToMapWay2(map, list));
    }

    /**
     * 处理集合数据转化为map(for循环方式)
     */
    private static Map<String,List<String>> listToMapWay1(Map<String,List<String>> map,List<String> list){
        Map<String,List<String>> resultMap = Optional.ofNullable(map).orElse(new HashMap<>());
        if (CollUtil.isEmpty(list)){
            return resultMap;
        }
        list.forEach(str -> {
            if (resultMap.containsKey(str)){
                List<String> mapValueList = resultMap.get(str);
                if (!mapValueList.contains(str)){
                    mapValueList.add(str);
                    resultMap.put(str,mapValueList);
                }
            } else {
               List<String> mapValueList = new ArrayList<>();
               mapValueList.add(str);
               resultMap.put(str,mapValueList);
            }
        });
        return resultMap;
    }

    /**
     * 处理集合数据转化为map(stream方式)
     */
    private static Map<String, List<String>> listToMapWay2(Map<String, List<String>> map, List<String> list) {
        if (CollUtil.isEmpty(list)) {
            return Optional.ofNullable(map).orElse(new HashMap<>());
        }
        return list.stream()
                .collect(Collectors.toMap(
                        str -> str,
                        str -> {
                            List<String> mapValueList = map.getOrDefault(str, new ArrayList<>());
                            if (!mapValueList.contains(str)) {
                                mapValueList.add(str);
                            }
                            return mapValueList;
                        },
                        (existingList, newList) -> existingList,
                        HashMap::new
                ));
    }
}
